import Vue from 'vue'
import Vuex from 'vuex'
import {
  areaCityQuest
} from '@/request/api.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { //状态管理
    areaProvinceCity: [],
    area: [],
    province: [],
    city: [],
  },
  mutations: { //修改数据
    getArea(state, res) { //第一个参数是state,用于管理state中的数据，
      state.areaProvinceCity = res;
      console.log("大区省份城市存储成功", state.areaProvinceCity);
      var arrData = [];
      for (var k = 0; k < res.length; k++) {
        let areaCode=res[k].aName+"_"+res[k].aCode;
        arrData.push(areaCode);//["华北大区,华南大区"]
      };
      //大区数组去重
      for (var i = 0; i < arrData.length; i++) {
        for (var j = i + 1; j < arrData.length; j++) {
          if (arrData[i] == arrData[j]) {
            arrData.splice(j, 1); //2,3
            j--;
          }
        }
      }
      state.area = arrData;
      localStorage.setItem("allArea", arrData);
      console.log("所有大区存储成功", state.area);

    },
    getprovince(state, res) {
      var allProvince = [];
      for (var i = 0; i < res.length; i++) {
        allProvince.push(res[i].pName)
      }
      //省份数组去重
      for (var j = 0; j < allProvince.length; j++) {
        for (var k = j + 1; k < allProvince.length; k++) {
          if (allProvince[j] == allProvince[k]) {
            allProvince.splice(k, 1);
            k--;
          }
        }
      }
      state.province = allProvince;
      localStorage.setItem("allProvince", allProvince);
      console.log("所有省份存储成功", state.province);
    },
    getCity(state, res) {
      var allCity = [];
      for (var i = 0; i < res.length; i++) {
        allCity.push(res[i].cName);
      }
      //城市数组去重
      for (var j = 0; j < allCity.length; j++) {
        for (var k = j + 1; k < allCity.length; k++) {
          if (allCity[j] == allCity[k]) {
            allCity.splice(k);
            k--;
          }
        }
      }
      state.city = allCity;
      localStorage.setItem("allCity", allCity);
      console.log("所有城市存储成功", allCity);
    }
  },
  actions: { //异步处理
    areaCityQuest(context, data) { //第一个参数是变量，这个变量相当于vuex的实例，有vuex的属性和方法
      console.log("pName是", data);
      areaCityQuest({
          aName: data[0] || null,
          pName: data[1] || null,
          cName: data[2] || null
        })
        .then(res => {
          console.log("大区城市调试成功", res.data.CityInfos);
          if (data[0] == null && data[1] == null && data[2] == null) { //不穿参数，获取所有大区数据
            context.commit('getArea', res.data.CityInfos)
          } else if (data[0] !== null && data[1] == null && data[2] == null) { //传大区,获取大区的省份
            context.commit('getprovince', res.data.CityInfos)
          } else if (data[0] !== null && data[1] !== null && data[2] == null) { //传大区和省份，获取省份的城市
            context.commit('getCity', res.data.CityInfos)
          }

        })
        .catch(err => {
          console.log("大区城市调试失败了", err);
        });
    },
  },
  modules: { //模块
  }
})